package com.lanswon.qzsmk.controller.cardManageController;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.CardProdunctDefinition;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.service.cardManageService.SellCardService;
import com.lanswon.qzsmk.service.systemManageService.ParamManageService;
import com.lanswon.qzsmk.vo.SellCardVo;

/**
 * 批量发卡Controller
 * @author guyawei
 *
 */
@Controller
@RequestMapping(value="/issueCardBatch")
public class GetCardBatchController {

	@Autowired
	SellCardService scs;
	
	@Autowired
	ParamManageService pm;
	
	/**
	 * 链接批量发卡页面
	 * @return
	 */
	@RequiresPermissions("issueCardBatch:index")
	@RequestMapping(value="/getCardBatch",name="批量发卡,issueCardBatch:index",method={RequestMethod.GET,RequestMethod.POST})
	public String getCardBatch(HttpServletRequest request){
		
		return "GetCardBatch";
	}
	
	
	/**
	 * 查询批量发卡信息
	 * @param scv
	 * @param startTime
	 * @param endTime
	 * @param pageCount
	 * @return
	 * @throws ParseException
	 */
	@RequiresPermissions("issueCardBatch:getCardBatchInfo")
	@RequestMapping(value="/getCardBatchInfo",name="批量发卡查询批量发卡信息,issueCardBatch:getCardBatchInfo",method=RequestMethod.POST)
	@ResponseBody
	public DwzPage<SellCardVo> getGetCardBatchInfo(SellCardVo scv,Integer pageNum,Integer numPerPage) throws ParseException{
//		if(scv.getNumPerPage()==null){//加载页面时执行
//			scv.setCurrentPage(1);
//			scv.setNumPerPage(20);
//		}else {
//			if(scv.getCurrentPage()<=1||pageCount==0){
//				scv.setCurrentPage(1);
//			}else if(scv.getCurrentPage()>=pageCount&&pageCount!=0){
//				scv.setCurrentPage(pageCount);
//			}
//		}
		System.out.println(pageNum+","+numPerPage+",");
		if(pageNum==null&&numPerPage==null){
			pageNum=1;
			numPerPage=20;	
		}
		scv.setCurrentPage(pageNum);
		scv.setNumPerPage(numPerPage);
		scv.setStartLine((scv.getCurrentPage()-1)*scv.getNumPerPage());
		DwzPage<SellCardVo> dPage=scs.queryBatchSellCard(scv);
		return dPage;
	}
	
	/**
	 * 批量发卡提交
	 * @param scv
	 * @param getCardBatch
	 * @return
	 * @throws Exception 
	 */
	@RequiresPermissions("issueCardBatch:commitBatch")
	@RequestMapping(value="/commitBatch",name="批量发卡提交,issueCardBatch:commitBatch",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> commitBatchByCheckBranchNo(SellCardVo scv,String[] getCardBatch,HttpServletRequest request) throws Exception{
		for(String str:getCardBatch){
			System.out.println(str);
		}
		Map<String, Object> map=new HashMap<>();
		ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		String [] s=getCardBatch[0].split("#");
		if(!activeUser.getBranchNo().equals(s[s.length-2])){
			map.put("statusCode", "300");
    		map.put("message", "此数据属于"+activeUser.getBranchName()+",无权操作");
    		return map;
		}
		scv.setApplyBatchNo(s[0]);
		scv.setRecordNum(Integer.valueOf(s[1]));
		scv.setCardPCodeName(s[2]);
		Cert cert=scs.commitBatchSellCardInfo(scv);
		CardProdunctDefinition cpd=pm.queryCardPCode(cert.getCardpCode());
		request.getSession().setAttribute("cert", cert);
		request.getSession().setAttribute("type", "batchCard");
		request.getSession().setAttribute("recordNum", scv.getRecordNum());
		request.getSession().setAttribute("cardpName", cpd.getCardpName());
		map.put("max", "true");
        map.put("title", "批量发卡凭证");
        map.put("rel", "cardbatch");
        map.put("statusCode", "200");
        map.put("url", "printCredentials/toReChargePdfView");
        map.put("jumpToTile", "批量发卡");
        map.put("jumpToTabid", "makeCardBatch");
        map.put("jumpToUrl", "makeCardBatch/batch");
		
		return map;
	}
	
	/**
	 * 这种下载方式  只能是表单提交
	 */
	@RequiresPermissions("issueCardBatch:download")
	@RequestMapping(value="/download",name="批量发卡下载,issueCardBatch:download",method=RequestMethod.POST)
	public void downloadSellCard(String applyBatchNo,String workCorp,HttpServletRequest request,HttpServletResponse response){
		
		String root =request.getSession().getServletContext().getRealPath("/");
		
		File f = scs.downloadSellCard(root, applyBatchNo, workCorp);
		
//		response.reset();// 不加这一句的话会出现下载错误 
			try {
				response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(f.getName(),"UTF-8"));
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				throw new SystemException(SystemException.UnsupportedEncodingException, "文件名转码异常");
			}
        // 设定输出文件头   
        response.setContentType("application/x-msdownload;charset=UTF-8");
        
        try {
            ServletOutputStream out =  response.getOutputStream();
			
            FileInputStream fis =new FileInputStream(f);
            
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096);
            
            byte[] cache = new byte[4096];
            for (int offset = fis.read(cache); offset != -1; offset = fis.read(cache)) {
                    byteOutputStream.write(cache, 0, offset);
            }
            byte[] bt = null;
            bt = byteOutputStream.toByteArray();               
           
				out.write(bt);
			
            out.flush();
            out.close();
            fis.close();
                      
            } catch (IOException e) {
            	e.printStackTrace();
            	
            	String msg="系统IO流异常";
    			
    			throw new SystemException(SystemException.IOException, msg);

    		}  
			
		
	}
	
	
	
}
